<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import qs from "qs";

// 初始化页面标题
document.title = "MMD模型资源管理中心 - 模型管理";
// 模型列表
const modelList = ref([])
const occupation = [
  {value: 'bladePoint', label: '刀锋'},
  {value: 'Flame', label: '烈焰'},
  {value: 'doubleGun', label: '双枪'},
  {value: 'machineGun', label: '机枪'},
  {value: 'guidedMissile', label: '导弹'},
  {value: 'sniper', label: '狙击'},
  {value: 'medic', label: '医生'},
  {value: 'grenade', label: '榴弹'},
  {value: 'engineer', label: '工程师'}
]
const style = {textAlign: 'center'}
// 模型对话框的可见性
const modelDialogVisible = ref(false);
// 对话框标题
const dialogTitle = ref('');
// 编辑状态标识
const isEditing = ref(false);
// 表单标签宽度
const formLabelWidth = ref('100px')
// 模型表单数据
const modelFormData = ref({
  modelName: '',
  modelOccupation: '',
  modelFile: null, // 替换modelUrl为文件上传
  modelImg: '',
  modelSource: '',
  boneBinding: '',
  physicsBinding: '',
  expressionMaking: '',
});

// 文件上传相关
const uploadRef = ref(null);
const uploadLoading = ref(false);
const modelIdData = ref([]); // 存储model_id表格数据
// 模型表单规则
const modelFormRules = ref({
  modelName: [
    {required: true, message: '请输入模型名称', trigger: 'blur'}
  ],
  modelOccupation: [
    {required: true, message: '请输入模型职业', trigger: 'blur'}
  ],
  modelFile: [
    {required: true, message: '请上传模型文件', trigger: 'change'}
  ],
  modelImg: [
    {required: true, message: '请输入模型图片链接', trigger: 'blur'}
  ]
})

// 搜索关键字
const search = ref("")
const occ = ref("")

// 表单组件引用
const modelFormRef = ref(null)
// 总模型数量
const totalModels = ref(0);
// 当前页码，默认为第一页
const currentPage = ref(1);
// 每页显示的条数，默认10
const pageSize = ref(10);

// 统计数据
const statistics = ref({
  total: 0,
  active: 0,
  inactive: 0,
  categories: 0
})

const getModelList = async () => {
  let res;
  try {
    if (search.value) {
      res = await axios.get("/api/v2/model/list", {
        params: {
          search: search.value,
          page: currentPage.value,
          size: pageSize.value
        }
      })
    } else if (occ.value) {
      res = await axios.get("/api/v2/model/list", {
        params: {
          occ: occ.value,
          page: currentPage.value,
          size: pageSize.value
        }
      })
    } else if(search.value && occ.value){
      res = await axios.get("/api/v2/model/list", {
        params: {
          search: search.value,
          occ: occ.value,
          page: currentPage.value,
          size: pageSize.value
        }
      })
    }else {
      res = await axios.get("/api/v2/model/list", {
        params: {
          page: currentPage.value,
          size: pageSize.value
        }
      })
    }
    
    // 如果API调用失败，使用模拟数据
    if (!res || !res.data) {
      // 生成模拟数据
      const mockData = generateMockData();
      modelList.value = mockData.data;
      totalModels.value = mockData.total;
    } else {
      // v2 统一分页结构：res.data.data => { data, total, current, size }
      const pageData = res.data.data || {}
      modelList.value = pageData.data || [];
      totalModels.value = pageData.total || (pageData.data ? pageData.data.length : 0);
    }
    
    // 更新统计数据
    updateStatistics()
  } catch (e) {
    // API调用失败时使用模拟数据
    const mockData = generateMockData();
    modelList.value = mockData.data;
    totalModels.value = mockData.total;
    updateStatistics();
    console.log('使用模拟数据:', e.message);
  }
}

// 生成模拟数据
const generateMockData = () => {
  const total = 156; // 总数据量
  const start = (currentPage.value - 1) * pageSize.value;
  const end = Math.min(start + pageSize.value, total);
  
  const mockModels = [];
  for (let i = start; i < end; i++) {
    mockModels.push({
      MId: i + 1,
      MName: `MMD模型_${i + 1}`,
      MOccupation: occupation[Math.floor(Math.random() * occupation.length)].value,
      MUrl: `https://example.com/model_${i + 1}.zip`,
      MImg: `https://via.placeholder.com/150x150/333/fff?text=Model_${i + 1}`,
      MModelSource: '游戏内提取',
      MBoneBinding: '已绑定',
      MPhysicsBinding: '已绑定',
      MExpressionMaking: '已制作'
    });
  }
  
  return {
    data: mockModels,
    total: total
  };
}

// 更新统计数据
const updateStatistics = () => {
  statistics.value = {
    total: totalModels.value,
    active: modelList.value.filter(item => item.status === 'active').length,
    inactive: modelList.value.filter(item => item.status === 'inactive').length,
    categories: new Set(modelList.value.map(item => item.MOccupation)).size
  }
}

// 执行搜索
const searchModel = () => {
  currentPage.value = 1; // 搜索时重置到第一页
  getModelList()
}
// 打开添加模型对话框
const openAddModelDialog = () => {
  isEditing.value = false;
  dialogTitle.value = '添加模型';
  modelDialogVisible.value = true;
  modelFormData.value = {
    modelId: 0, 
    modelName: '', 
    modelOccupation: '', 
    modelFile: null, // 使用文件上传
    modelImg: '', 
    modelSource: '游戏内提取', 
    boneBinding: '已绑定', 
    physicsBinding: '已绑定', 
    expressionMaking: '已制作'
  };
}
// 添加模型
const addModel = async () => {
  try {
    // 如果有文件需要上传，先上传文件
    if (modelFormData.value.modelFile) {
      uploadLoading.value = true;
      const formData = new FormData();
      formData.append('file', modelFormData.value.modelFile);
      
      const uploadRes = await axios.post("/api/v2/model/upload", formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      
      if (uploadRes.data.code === 200) {
        modelFormData.value.modelUrl = uploadRes.data.data.url;
      } else {
        ElMessage.error('文件上传失败：' + uploadRes.data.msg);
        uploadLoading.value = false;
        return;
      }
      uploadLoading.value = false;
    }
    
    // 准备提交的数据（排除文件对象）
    const submitData = {
      ...modelFormData.value,
      modelFile: undefined // 移除文件对象
    };
    
    const res = await axios.post("/api/v2/model/add", submitData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    if (res.data.code === 200) {
      ElMessage.success("添加模型成功!!")
      modelDialogVisible.value = false;
      await getModelList()
      // 通知仪表板更新统计数据
      localStorage.setItem('dashboardRefresh', Date.now().toString())
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (e) {
    uploadLoading.value = false;
    ElMessage.error(`服务器异常,添加模型失败,请联系管理员！错误：${e.message}`)
  }
}
// 打开编辑模型对话框
const openEditModelDialog = (model) => {
  isEditing.value = true;
  dialogTitle.value = '编辑模型';
  modelDialogVisible.value = true;
  modelFormData.value = {
    modelId: model.MId,
    modelName: model.MName,
    modelOccupation: model.MOccupation,
    modelUrl: model.MUrl,
    modelImg: model.MImg,
    modelSource: model.MModelSource || '游戏内提取',
    boneBinding: model.MBoneBinding || '已绑定',
    physicsBinding: model.MPhysicsBinding || '已绑定',
    expressionMaking: model.MExpressionMaking || '已制作',
  };
}
// 更新模型
const updateModel = async () => {
  try {
    const res = await axios.post("/api/v2/model/update", modelFormData.value, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    if (res.data.code === 200) {
      ElMessage.success("更新模型成功!!")
      modelDialogVisible.value = false;
      await getModelList()
      // 通知仪表板更新统计数据
      localStorage.setItem('dashboardRefresh', Date.now().toString())
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (e) {
    ElMessage.error(`服务器异常,更新模型失败,请联系管理员！错误：${e.message}`)
  }
}
// 刷新模型列表
const refreshModel = () => {
  search.value = "";
  occ.value = ""
  currentPage.value = 1; // 重置到第一页
  getModelList()
}
// 删除模型（目前未实现）
const deleteModel = row => {
  ElMessage.warning("删除模型功能暂未开放!")
}
// 确认按钮点击事件，验证表单并提交
const onConfirmButtonClick = () => {
  modelFormRef.value.validate((valid) => {
    if (valid) {
      confirmModelDialog(); // 如果验证通过，则执行模型的添加或更新
    } else {
      ElMessage.error('表单数据有误，请检查后再试');
      return false;
    }
  });
};
// 执行模型添加或更新
const confirmModelDialog = async () => {
  if (isEditing.value) {
    await updateModel(); // 调用编辑模型的API
  } else {
    await addModel(); // 调用添加模型的API
  }
}
// 关闭模型对话框
const closeModelDialog = () => {
  modelDialogVisible.value = false;
}
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  getModelList()
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1; // 重置到第一页
  getModelList()
};
// 获取model_id表格数据
const getModelIdData = async () => {
  console.log('开始获取model_id数据...');
  try {
    const res = await axios.get("/api/v2/model/modelIds");
    console.log('API响应:', res.data);
    if (res.data.code === 200) {
      modelIdData.value = res.data.data || [];
      console.log('成功获取API数据:', modelIdData.value);
    } else {
      console.log('API返回错误，使用模拟数据');
      // 使用模拟数据
      modelIdData.value = [
        { m_id: 101011000, m_name: "经典刀锋皮肤", m_occupation: "bladePoint" },
        { m_id: 101011001, m_name: "血腥玛丽", m_occupation: "bladePoint" },
        { m_id: 101011002, m_name: "王女艾琳", m_occupation: "bladePoint" },
        { m_id: 101011003, m_name: "捕猎少女欧丽莎", m_occupation: "bladePoint" },
        { m_id: 101011004, m_name: "炫彩之影·曼尼莎", m_occupation: "bladePoint" },
        { m_id: 101011005, m_name: "泳衣刀锋", m_occupation: "bladePoint" },
        { m_id: 101011006, m_name: "灵魂圣女·柯莉丝汀", m_occupation: "bladePoint" },
        { m_id: 101011007, m_name: "烈焰女皇", m_occupation: "Flame" },
        { m_id: 101011008, m_name: "火焰舞者", m_occupation: "Flame" },
        { m_id: 101011009, m_name: "双枪手", m_occupation: "doubleGun" }
      ];
      console.log('使用模拟数据:', modelIdData.value);
    }
  } catch (e) {
    console.log('API调用异常，使用模拟数据:', e.message);
    // 使用模拟数据
    modelIdData.value = [
      { m_id: 101011000, m_name: "经典刀锋皮肤", m_occupation: "bladePoint" },
      { m_id: 101011001, m_name: "血腥玛丽", m_occupation: "bladePoint" },
      { m_id: 101011002, m_name: "王女艾琳", m_occupation: "bladePoint" },
      { m_id: 101011003, m_name: "捕猎少女欧丽莎", m_occupation: "bladePoint" },
      { m_id: 101011004, m_name: "炫彩之影·曼尼莎", m_occupation: "bladePoint" },
      { m_id: 101011005, m_name: "泳衣刀锋", m_occupation: "bladePoint" },
      { m_id: 101011006, m_name: "灵魂圣女·柯莉丝汀", m_occupation: "bladePoint" },
      { m_id: 101011007, m_name: "烈焰女皇", m_occupation: "Flame" },
      { m_id: 101011008, m_name: "火焰舞者", m_occupation: "Flame" },
      { m_id: 101011009, m_name: "双枪手", m_occupation: "doubleGun" }
    ];
    console.log('使用模拟数据:', modelIdData.value);
  }
  console.log('getModelIdData完成，当前数据长度:', modelIdData.value.length);
}

// 根据模型名称动态匹配model_id
const matchModelId = (modelName) => {
  if (!modelName || !modelIdData.value.length) {
    return null;
  }
  
  // 精确匹配
  let match = modelIdData.value.find(item => item.m_name === modelName);
  if (match) {
    return match;
  }
  
  // 模糊匹配
  match = modelIdData.value.find(item => 
    modelName.includes(item.m_name) || item.m_name.includes(modelName)
  );
  if (match) {
    return match;
  }
  
  // 关键词匹配
  const keywords = modelName.split(/[\s\-·]+/);
  for (const keyword of keywords) {
    if (keyword.length > 1) {
      match = modelIdData.value.find(item => 
        item.m_name.includes(keyword)
      );
      if (match) {
        return match;
      }
    }
  }
  
  return null;
}

// 监听模型名称变化，自动匹配
const onModelNameChange = () => {
  // 临时调试信息
  console.log('=== 自动匹配调试信息 ===');
  console.log('输入框值:', modelFormData.value.modelName);
  console.log('modelIdData长度:', modelIdData.value.length);
  console.log('modelIdData内容:', modelIdData.value);
  
  const modelName = modelFormData.value.modelName;
  if (modelName && modelIdData.value.length > 0) {
    const match = matchModelId(modelName);
    console.log('匹配结果:', match);
    if (match) {
      modelFormData.value.modelOccupation = match.m_occupation;
      modelFormData.value.modelImg = `https://model.lovemmd.cn/img/${match.m_id}.png`;
      ElMessage.success(`自动匹配成功：职业 ${getOccupationLabel(match.m_occupation)}`);
      console.log('自动填充完成:', {
        occupation: modelFormData.value.modelOccupation,
        img: modelFormData.value.modelImg
      });
    } else {
      console.log('没有找到匹配项');
    }
  } else {
    console.log('条件不满足:', {
      hasModelName: !!modelName,
      hasData: modelIdData.value.length > 0
    });
  }
}

// 获取职业标签
const getOccupationLabel = (occupationValue) => {
  const occ = occupation.find(item => item.value === occupationValue);
  return occ ? occ.label : occupationValue;
}

// 文件上传处理
const handleFileUpload = (file) => {
  // 检查文件类型
  const allowedTypes = ['.pmx', '.pmd', '.zip', '.rar', '.7z'];
  const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  
  if (!allowedTypes.includes(fileExtension)) {
    ElMessage.error('只支持 .pmx, .pmd, .zip, .rar, .7z 格式的文件');
    return false;
  }
  
  // 检查文件大小 (50MB)
  const maxSize = 50 * 1024 * 1024;
  if (file.size > maxSize) {
    ElMessage.error('文件大小不能超过50MB');
    return false;
  }
  
  modelFormData.value.modelFile = file;
  return false; // 阻止自动上传
}

// 文件上传成功回调
const onUploadSuccess = (response, file) => {
  uploadLoading.value = false;
  if (response.code === 200) {
    ElMessage.success('文件上传成功');
    modelFormData.value.modelUrl = response.data.url; // 保存上传后的URL
  } else {
    ElMessage.error(response.msg || '文件上传失败');
  }
}

// 文件上传失败回调
const onUploadError = (error) => {
  uploadLoading.value = false;
  ElMessage.error('文件上传失败：' + error.message);
}

// 页面加载时获取模型列表
onMounted(() => {
  getModelList();
  getModelIdData(); // 获取model_id数据
})
</script>

<template>
  <div class="model-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">模型管理</h1>
        <p class="page-subtitle">管理MMD模型资源，包括添加、编辑、删除和查看模型信息</p>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="statistics-section">
      <div class="stat-card">
        <div class="stat-icon total">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
            <path d="M2 17L12 22L22 17" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
            <path d="M2 12L12 17L22 12" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
          </svg>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.total }}</div>
          <div class="stat-label">总模型数</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon active">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M9 12L11 14L15 10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" stroke-width="2"/>
          </svg>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.active }}</div>
          <div class="stat-label">活跃模型</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon categories">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M3 3H21V7H3V3Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M3 10H21V14H3V10Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M3 17H21V21H3V17Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.categories }}</div>
          <div class="stat-label">MMD模型分类</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon inactive">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M18.364 18.364A9 9 0 1 1 5.636 5.636A9 9 0 0 1 18.364 18.364Z" stroke="currentColor" stroke-width="2"/>
            <path d="M15.5355 8.46447L8.46447 15.5355" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
          </svg>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.inactive }}</div>
          <div class="stat-label">停用模型</div>
        </div>
      </div>
    </div>

    <!-- 操作栏 -->
    <div class="action-section">
      <div class="action-left">
        <el-button 
          type="primary" 
          class="action-button primary"
          @click="openAddModelDialog"
        >
          <el-icon><Plus /></el-icon>
          <span>发布模型</span>
        </el-button>
        
        <el-button 
          class="action-button secondary"
          @click="refreshModel"
        >
          <el-icon><Refresh /></el-icon>
          <span>刷新列表</span>
        </el-button>
      </div>

      <div class="action-right">
        <div class="search-filters">
          <el-input 
            v-model="search" 
            placeholder="搜索模型名称..."
            class="search-input"
            clearable
            prefix-icon="Search"
          />
          
          <el-select 
            v-model="occ" 
            placeholder="选择职业分类"
            class="filter-select"
            clearable
          >
            <el-option
              v-for="item in occupation"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          
          <el-button 
            type="primary" 
            class="search-button"
            @click="searchModel"
          >
            搜索
          </el-button>
        </div>
      </div>
    </div>

    <!-- 模型列表 -->
    <div class="table-section">
      <div class="table-container">
        <el-table 
          :data="modelList" 
          :header-cell-style="style" 
          class="model-table"
          stripe
          border
        >
          <el-table-column 
            align="center" 
            label="模型ID" 
            prop="MId" 
            width="100"
            class-name="id-column"
          />
          
          <el-table-column 
            align="center" 
            label="模型名称" 
            prop="MName" 
            width="250"
            class-name="name-column"
          />
          
          <el-table-column 
            align="center" 
            label="模型职业" 
            prop="MOccupation" 
            width="150"
            class-name="occupation-column"
          >
            <template #default="scope">
              <div v-for="item in occupation" :key="item.value">
                <el-tag 
                  v-if="scope.row.MOccupation === item.value" 
                  type="success"
                  class="occupation-tag"
                >
                  {{ item.label }}
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column 
            align="center" 
            label="图片路径" 
            prop="MImg" 
            width="200"
            class-name="image-column"
          >
            <template #default="scope">
              <div class="image-preview">
                <img 
                  v-if="scope.row.MImg" 
                  :src="scope.row.MImg" 
                  alt="模型图片"
                  class="model-image"
                  @error="$event.target.style.display='none'"
                />
                <span v-else class="no-image">无图片</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column 
            align="center" 
            label="下载地址" 
            prop="MUrl" 
            width="250"
            class-name="url-column"
          >
            <template #default="scope">
              <div class="url-cell">
                <el-link 
                  :href="scope.row.MUrl" 
                  target="_blank"
                  type="primary"
                  class="download-link"
                >
                  <el-icon><Download /></el-icon>
                  <span>下载</span>
                </el-link>
                <el-tooltip 
                  :content="scope.row.MUrl" 
                  placement="top"
                  :show-after="500"
                >
                  <div class="url-text" :title="scope.row.MUrl">
                    {{ scope.row.MUrl }}
                  </div>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>

          <el-table-column 
            align="center" 
            label="模型来源" 
            prop="MModelSource" 
            width="120"
            class-name="source-column"
          />

          <el-table-column 
            align="center" 
            label="骨骼绑定" 
            prop="MBoneBinding" 
            width="120"
            class-name="bone-column"
          />

          <el-table-column 
            align="center" 
            label="物理绑定" 
            prop="MPhysicsBinding" 
            width="120"
            class-name="physics-column"
          />

          <el-table-column 
            align="center" 
            label="表情制作" 
            prop="MExpressionMaking" 
            width="120"
            class-name="expression-column"
          />
          
          <el-table-column 
            label="操作" 
            width="200"
            class-name="action-column"
          >
            <template #default="scope">
              <div class="action-buttons">
                <el-button 
                  type="primary" 
                  size="small"
                  class="edit-button"
                  @click="openEditModelDialog(scope.row)"
                >
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                
                <el-button 
                  type="danger" 
                  size="small"
                  class="delete-button"
                  @click="deleteModel(scope.row)"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :background="true"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalModels"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          class="pagination"
        />
      </div>
    </div>

    <!-- 模型对话框 -->
    <el-dialog 
      v-model="modelDialogVisible" 
      :title="dialogTitle" 
      @close="closeModelDialog"
      class="model-dialog"
      width="600px"
    >
      <el-form 
        ref="modelFormRef" 
        :model="modelFormData" 
        :rules="modelFormRules"
        label-position="top"
        class="model-form"
      >
        <el-form-item 
          v-if="isEditing" 
          label="模型ID" 
          prop="modelId"
        >
          <el-input 
            v-model="modelFormData.modelId" 
            disabled
            class="form-input"
          />
        </el-form-item>
        
                 <el-form-item label="模型名称" prop="modelName">
           <el-input 
             v-model="modelFormData.modelName" 
             placeholder="请输入模型名称（输入后会自动匹配职业和图片）"
             class="form-input"
             @input="onModelNameChange"
           />
         </el-form-item>
        
                 <el-form-item label="模型职业" prop="modelOccupation">
           <el-select 
             v-model="modelFormData.modelOccupation" 
             placeholder="请选择职业（会根据模型名称自动匹配）"
             class="form-select"
           >
             <el-option
               v-for="item in occupation"
               :key="item.value"
               :label="item.label"
               :value="item.value"
             />
           </el-select>
         </el-form-item>
        
                 <el-form-item label="模型文件" prop="modelFile">
           <el-upload
             ref="uploadRef"
             :auto-upload="false"
             :show-file-list="true"
             :limit="1"
             :on-change="handleFileUpload"
             :on-success="onUploadSuccess"
             :on-error="onUploadError"
             :file-list="modelFormData.modelFile ? [modelFormData.modelFile] : []"
             class="model-upload"
             accept=".pmx,.pmd,.zip,.rar,.7z"
           >
             <el-button 
               type="primary" 
               :loading="uploadLoading"
               class="upload-button"
             >
               <el-icon><Upload /></el-icon>
               选择模型文件
             </el-button>
             <template #tip>
               <div class="upload-tip">
                 支持 .pmx, .pmd, .zip, .rar, .7z 格式，文件大小不超过50MB
               </div>
             </template>
           </el-upload>
         </el-form-item>
        
                 <el-form-item label="模型图片" prop="modelImg">
           <el-input 
             v-model="modelFormData.modelImg" 
             placeholder="图片URL会根据模型名称自动生成"
             class="form-input"
             readonly
           />
           <div class="image-preview-container" v-if="modelFormData.modelImg">
             <img 
               :src="modelFormData.modelImg" 
               alt="模型图片预览"
               class="image-preview"
               @error="$event.target.style.display='none'"
             />
           </div>
         </el-form-item>

        <el-form-item label="模型来源" prop="modelSource">
          <el-select 
            v-model="modelFormData.modelSource" 
            placeholder="请选择模型来源"
            class="form-select"
          >
            <el-option label="游戏内提取" value="游戏内提取" />
            <el-option label="官方发布" value="官方发布" />
            <el-option label="二次创作" value="二次创作" />
            <el-option label="第三方制作" value="第三方制作" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>

        <el-form-item label="骨骼绑定" prop="boneBinding">
          <el-select 
            v-model="modelFormData.boneBinding" 
            placeholder="请选择骨骼绑定状态"
            class="form-select"
          >
            <el-option label="已绑定" value="已绑定" />
            <el-option label="未绑定" value="未绑定" />
            <el-option label="部分绑定" value="部分绑定" />
          </el-select>
        </el-form-item>

        <el-form-item label="物理绑定" prop="physicsBinding">
          <el-select 
            v-model="modelFormData.physicsBinding" 
            placeholder="请选择物理绑定状态"
            class="form-select"
          >
            <el-option label="已绑定" value="已绑定" />
            <el-option label="未绑定" value="未绑定" />
            <el-option label="部分绑定" value="部分绑定" />
          </el-select>
        </el-form-item>

        <el-form-item label="表情制作" prop="expressionMaking">
          <el-select 
            v-model="modelFormData.expressionMaking" 
            placeholder="请选择表情制作状态"
            class="form-select"
          >
            <el-option label="已制作" value="已制作" />
            <el-option label="未制作" value="未制作" />
            <el-option label="部分制作" value="部分制作" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeModelDialog" class="cancel-button">
            取消
          </el-button>
          <el-button 
            type="primary" 
            @click="onConfirmButtonClick"
            class="confirm-button"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.model-management {
  padding: 0;
}

/* 页面标题 */
.page-header {
  margin-bottom: 2rem;
}

.header-content {
  text-align: center;
}

.page-title {
  font-size: 2rem;
  font-weight: 700;
  color: var(--gold-primary);
  margin: 0 0 0.5rem 0;
  background: var(--gradient-gold);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-subtitle {
  color: var(--text-muted);
  font-size: 1rem;
  margin: 0;
}

/* 统计卡片 */
.statistics-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.stat-card {
  background: var(--gradient-card);
  border: 1px solid var(--border-gold);
  border-radius: 12px;
  padding: 1.5rem;
  display: flex;
  align-items: center;
  gap: 1rem;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px var(--shadow-dark);
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px var(--shadow-gold);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--primary-black);
  font-size: 1.5rem;
}

.stat-icon.total {
  background: var(--gradient-gold);
}

.stat-icon.active {
  background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
}

.stat-icon.categories {
  background: linear-gradient(135deg, #007bff 0%, #6610f2 100%);
}

.stat-icon.inactive {
  background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
}

.stat-icon svg {
  width: 30px;
  height: 30px;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 2rem;
  font-weight: 700;
  color: var(--text-primary);
  line-height: 1;
  margin-bottom: 0.25rem;
}

.stat-label {
  color: var(--text-muted);
  font-size: 0.9rem;
}

/* 操作栏 */
.action-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  gap: 1rem;
  flex-wrap: wrap;
}

.action-left {
  display: flex;
  gap: 1rem;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.action-button.primary {
  background: var(--gradient-gold) !important;
  border: 1px solid var(--gold-primary) !important;
  color: var(--primary-black) !important;
}

.action-button.primary:hover {
  background: var(--gold-accent) !important;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px var(--shadow-gold);
}

.action-button.secondary {
  background: var(--tertiary-black) !important;
  border: 1px solid var(--border-dark) !important;
  color: var(--text-secondary) !important;
}

.action-button.secondary:hover {
  background: var(--secondary-black) !important;
  border-color: var(--gold-primary) !important;
  color: var(--gold-primary) !important;
  transform: translateY(-2px);
}

.action-right {
  display: flex;
  align-items: center;
}

.search-filters {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.search-input {
  width: 250px;
}

.filter-select {
  width: 180px;
}

.search-button {
  padding: 0.75rem 1.5rem;
}

/* 表格区域 */
.table-section {
  background: var(--gradient-card);
  border: 1px solid var(--border-gold);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 24px var(--shadow-dark);
}

.table-container {
  overflow-x: auto;
}

.model-table {
  width: 100%;
}

.model-table :deep(.el-table__header) {
  background: var(--secondary-black);
}

.model-table :deep(.el-table__header th) {
  background: var(--secondary-black) !important;
  color: var(--gold-primary) !important;
  font-weight: 600 !important;
  border-bottom: 1px solid var(--border-gold) !important;
}

.model-table :deep(.el-table__body tr) {
  background: var(--tertiary-black) !important;
}

.model-table :deep(.el-table__body tr:hover > td) {
  background: var(--secondary-black) !important;
}

.model-table :deep(.el-table__body td) {
  border-bottom: 1px solid var(--border-dark) !important;
  color: var(--text-secondary) !important;
}

/* 表格列样式 */
.id-column {
  font-weight: 600;
  color: var(--gold-primary) !important;
}

.name-column {
  font-weight: 500;
  color: var(--text-primary) !important;
}

.occupation-tag {
  background: var(--gradient-gold) !important;
  color: var(--primary-black) !important;
  border: none !important;
  font-weight: 600 !important;
}

.image-preview {
  display: flex;
  justify-content: center;
  align-items: center;
}

.model-image {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  object-fit: cover;
  border: 1px solid var(--border-dark);
}

.no-image {
  color: var(--text-muted);
  font-size: 0.8rem;
}

.url-cell {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  align-items: center;
}

.download-link {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  font-weight: 600;
}

.url-text {
  font-size: 0.8rem;
  color: var(--text-muted);
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}

.action-buttons {
  display: flex;
  gap: 0.5rem;
  justify-content: center;
}

.edit-button, .delete-button {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  font-weight: 600;
}

/* 分页 */
.pagination-section {
  padding: 1.5rem;
  display: flex;
  justify-content: center;
  border-top: 1px solid var(--border-dark);
}

.pagination {
  background: transparent;
}

/* 对话框 */
.model-dialog :deep(.el-dialog__header) {
  background: var(--secondary-black);
  border-bottom: 1px solid var(--border-gold);
  padding: 1.5rem;
}

.model-dialog :deep(.el-dialog__title) {
  color: var(--gold-primary);
  font-weight: 600;
  font-size: 1.2rem;
}

.model-dialog :deep(.el-dialog__body) {
  padding: 2rem;
  background: var(--gradient-card);
}

.model-form {
  display: grid;
  gap: 1.5rem;
}

.form-input, .form-select {
  width: 100%;
}

.model-dialog :deep(.el-form-item__label) {
  color: var(--text-secondary);
  font-weight: 500;
  margin-bottom: 0.5rem;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  padding: 1.5rem;
  background: var(--secondary-black);
  border-top: 1px solid var(--border-gold);
}

.cancel-button {
  background: var(--tertiary-black) !important;
  border: 1px solid var(--border-dark) !important;
  color: var(--text-secondary) !important;
}

 .confirm-button {
   background: var(--gradient-gold) !important;
   border: 1px solid var(--gold-primary) !important;
   color: var(--primary-black) !important;
   font-weight: 600 !important;
 }

/* 文件上传样式 */
.model-upload {
   width: 100%;
 }

.upload-button {
   background: var(--gradient-gold) !important;
   border: 1px solid var(--gold-primary) !important;
   color: var(--primary-black) !important;
   font-weight: 600 !important;
   width: 100%;
   height: 40px;
 }

.upload-button:hover {
   background: var(--gold-accent) !important;
   transform: translateY(-1px);
   box-shadow: 0 4px 12px var(--shadow-gold);
 }

.upload-tip {
   color: var(--text-muted);
   font-size: 0.8rem;
   margin-top: 0.5rem;
   line-height: 1.4;
 }

/* 图片预览样式 */
.image-preview-container {
   margin-top: 0.5rem;
   display: flex;
   justify-content: center;
 }

.image-preview {
   width: 80px;
   height: 80px;
   border-radius: 8px;
   object-fit: cover;
   border: 2px solid var(--border-gold);
   box-shadow: 0 2px 8px var(--shadow-dark);
   transition: all 0.3s ease;
 }

.image-preview:hover {
   transform: scale(1.05);
   box-shadow: 0 4px 16px var(--shadow-gold);
 }

/* 响应式设计 */
@media (max-width: 768px) {
  .statistics-section {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .action-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .action-left, .action-right {
    justify-content: center;
  }
  
  .search-filters {
    flex-direction: column;
    width: 100%;
  }
  
  .search-input, .filter-select {
    width: 100%;
  }
  
  .page-title {
    font-size: 1.5rem;
  }
}

@media (max-width: 480px) {
  .statistics-section {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .model-table {
    font-size: 0.8rem;
  }
}
</style>